/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.ExpressQueryDto;
import com.yami.shop.bean.app.dto.FaceDesignOrderDto;
import com.yami.shop.bean.dto.PayDto;
import com.yami.shop.bean.model.FaceDesignOrder;
import com.yami.shop.bean.param.ExpressQueryParam;
import com.yami.shop.bean.param.FaceDesignOrderParam;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.Express100Service;
import com.yami.shop.service.FaceDesignOrderService;
import com.yami.shop.service.FaceDraftService;
import com.yami.shop.api.utils.WeixinUtils;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 人脸设计订单接口
 *
 * @author AI Assistant
 */
@RestController
@RequestMapping("/p/faceDesignOrder")
@Tag(name = "人脸设计订单接口")
public class FaceDesignOrderController {

    @Autowired
    private FaceDesignOrderService faceDesignOrderService;

    @Autowired
    private Express100Service express100Service;

    @Autowired
    private FaceDraftService faceDraftService;

    @Autowired
    private com.yami.shop.api.controller.WxPayController wxPayController;

    @Autowired
    private WeixinUtils weixinUtils;

    /**
     * 获取订单列表（分页）
     */
    @GetMapping("/page")
    @Operation(summary = "获取订单列表" , description = "分页获取订单列表")
    @Parameter(name = "status", description = "订单状态（0:待支付, 1:待发货, 2:待收货, 3:已完成, 4:已取消, 5:退款中, 6:已退款）", required = false)
    @Parameter(name = "payStatus", description = "支付状态（0:未支付, 1:已支付）", required = false)
    public ServerResponseEntity<IPage<FaceDesignOrderDto>> page(
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "payStatus", required = false) Integer payStatus,
            PageParam<FaceDesignOrder> page) {

        String userId = SecurityUtils.getUser().getUserId();
        FaceDesignOrderParam orderParam = new FaceDesignOrderParam();
        orderParam.setUserId(userId);
        orderParam.setStatus(status);
        orderParam.setPayStatus(payStatus);

        IPage<FaceDesignOrder> orderPage = faceDesignOrderService.pageByOrderParam(page, orderParam);
        IPage<FaceDesignOrderDto> orderDtoPage = orderPage.convert(order -> {
            FaceDesignOrderDto orderDto = BeanUtil.copyProperties(order, FaceDesignOrderDto.class);

            // 获取关联的faceDraft信息
            if (order.getDraftId() != null) {
                com.yami.shop.bean.model.FaceDraft faceDraft = faceDraftService.getById(order.getDraftId());
                if (faceDraft != null) {
                    com.yami.shop.bean.app.dto.FaceDraftDto faceDraftDto = BeanUtil.copyProperties(faceDraft, com.yami.shop.bean.app.dto.FaceDraftDto.class);
                    orderDto.setFaceDraft(faceDraftDto);
                }
            }

            return orderDto;
        });

        return ServerResponseEntity.success(orderDtoPage);
    }

    /**
     * 获取订单列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取订单列表" , description = "获取订单列表")
    @Parameter(name = "status", description = "订单状态（0:待支付, 1:待发货, 2:待收货, 3:已完成, 4:已取消, 5:退款中, 6:已退款）", required = false)
    @Parameter(name = "payStatus", description = "支付状态（0:未支付, 1:已支付）", required = false)
    public ServerResponseEntity<List<FaceDesignOrderDto>> list(
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "payStatus", required = false) Integer payStatus) {

        String userId = SecurityUtils.getUser().getUserId();
        FaceDesignOrderParam orderParam = new FaceDesignOrderParam();
        orderParam.setUserId(userId);
        orderParam.setStatus(status);
        orderParam.setPayStatus(payStatus);

        List<FaceDesignOrder> orderList = faceDesignOrderService.listByOrderParam(orderParam);
        List<FaceDesignOrderDto> orderDtoList = BeanUtil.copyToList(orderList, FaceDesignOrderDto.class);

        return ServerResponseEntity.success(orderDtoList);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/info")
    @Operation(summary = "获取订单详情" , description = "根据订单ID获取详情")
    @Parameter(name = "orderId", description = "订单ID", required = true)
    public ServerResponseEntity<FaceDesignOrderDto> info(@RequestParam("orderId") Long orderId) {

        String userId = SecurityUtils.getUser().getUserId();
        FaceDesignOrder order = faceDesignOrderService.getById(orderId);
        if (order == null) {
            return ServerResponseEntity.showFailMsg("订单不存在");
        }

        // 校验用户权限
        if (!order.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限查看该订单");
        }

        FaceDesignOrderDto orderDto = BeanUtil.copyProperties(order, FaceDesignOrderDto.class);
        return ServerResponseEntity.success(orderDto);
    }

    /**
     * 根据订单编号获取订单详情
     */
    @GetMapping("/infoByNumber")
    @Operation(summary = "根据订单编号获取订单详情" , description = "根据订单编号获取详情")
    @Parameter(name = "orderNumber", description = "订单编号", required = true)
    public ServerResponseEntity<FaceDesignOrderDto> infoByNumber(@RequestParam("orderNumber") String orderNumber) {

        String userId = SecurityUtils.getUser().getUserId();
        FaceDesignOrder order = faceDesignOrderService.getByOrderNumber(orderNumber);
        if (order == null) {
            return ServerResponseEntity.showFailMsg("订单不存在");
        }

        // 校验用户权限
        if (!order.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限查看该订单");
        }

        FaceDesignOrderDto orderDto = BeanUtil.copyProperties(order, FaceDesignOrderDto.class);
        return ServerResponseEntity.success(orderDto);
    }

    /**
     * 创建订单
     */
    @PostMapping("/create")
    @Operation(summary = "创建订单" , description = "创建新的订单")
    public ServerResponseEntity<String> create(@RequestBody FaceDesignOrderDto orderDto) {
        String userId = SecurityUtils.getUser().getUserId();
        orderDto.setUserId(userId);
        FaceDesignOrder order = BeanUtil.copyProperties(orderDto, FaceDesignOrder.class);
        String orderNumber = faceDesignOrderService.createOrder(order);
        return ServerResponseEntity.success(orderNumber);
    }

    /**
     * 支付订单
     */
    @PostMapping("/pay")
    @Operation(summary = "支付订单" , description = "支付订单")
    @Parameter(name = "orderNumber", description = "订单编号", required = true)
    @Parameter(name = "payType", description = "支付方式（1:微信, 2:支付宝）", required = true)
    @Parameter(name = "wxCode", description = "微信授权码（微信支付时必传）", required = false)
    @Parameter(name = "openId", description = "用户openId（微信支付时必传）", required = false)
    public ServerResponseEntity<Object> pay(
            @RequestParam("orderNumber") String orderNumber,
            @RequestParam("payType") Integer payType,
            @RequestParam(value = "wxCode", required = false) String wxCode,
            @RequestParam(value = "openId", required = false) String openId) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesignOrder order = faceDesignOrderService.getByOrderNumber(orderNumber);
        if (order == null) {
            return ServerResponseEntity.showFailMsg("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限支付该订单");
        }

        // 生成支付流水号
        String payNo = "PAY" + System.currentTimeMillis();

        // 微信支付逻辑
        if (payType == 1) {
            // 微信支付：调用微信支付接口
            if (openId == null || openId.isEmpty()) {
                if (wxCode == null || wxCode.isEmpty()) {
                    return ServerResponseEntity.showFailMsg("微信支付需要提供openId或wxCode");
                }
                // 通过wxCode获取openId
                openId = weixinUtils.getOpenIdByCode(wxCode);
            }

            // 构建PayDto
            PayDto payDto = new PayDto();
            payDto.setAmount(order.getOrderAmount());
            payDto.setTitle("人脸设计订单支付");
            payDto.setPayNo(orderNumber);
            payDto.setOpenid(openId);

            // 调用微信支付
            try {
                JSONObject payResult = wxPayController.jsapiPay(payDto);

                // 更新订单状态为待支付
                faceDesignOrderService.payOrder(orderNumber, payType, payNo);

                return ServerResponseEntity.success(payResult);
            } catch (Exception e) {
                return ServerResponseEntity.showFailMsg("微信支付调用失败：" + e.getMessage());
            }
        } else {
            // 其他支付方式：直接设置为已支付
            faceDesignOrderService.payOrder(orderNumber, payType, payNo);
            return ServerResponseEntity.success();
        }
    }

    /**
     * 取消订单
     */
    @PostMapping("/cancel")
    @Operation(summary = "取消订单" , description = "取消订单")
    @Parameter(name = "orderNumber", description = "订单编号", required = true)
    public ServerResponseEntity<Void> cancel(@RequestParam("orderNumber") String orderNumber) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesignOrder order = faceDesignOrderService.getByOrderNumber(orderNumber);
        if (order == null) {
            return ServerResponseEntity.showFailMsg("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限取消该订单");
        }

        faceDesignOrderService.cancelOrder(orderNumber, userId, "用户主动取消");
        return ServerResponseEntity.success();
    }

    /**
     * 确认收货
     */
    @PostMapping("/confirmReceive")
    @Operation(summary = "确认收货" , description = "确认收货")
    @Parameter(name = "orderNumber", description = "订单编号", required = true)
    public ServerResponseEntity<Void> confirmReceive(@RequestParam("orderNumber") String orderNumber) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesignOrder order = faceDesignOrderService.getByOrderNumber(orderNumber);
        if (order == null) {
            return ServerResponseEntity.showFailMsg("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限确认收货");
        }

        faceDesignOrderService.confirmReceive(orderNumber, userId);
        return ServerResponseEntity.success();
    }

    /**
     * 申请退款
     */
    @PostMapping("/applyRefund")
    @Operation(summary = "申请退款" , description = "申请退款")
    @Parameter(name = "orderNumber", description = "订单编号", required = true)
    @Parameter(name = "reason", description = "退款原因", required = true)
    public ServerResponseEntity<Void> applyRefund(
            @RequestParam("orderNumber") String orderNumber,
            @RequestParam("reason") String reason) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesignOrder order = faceDesignOrderService.getByOrderNumber(orderNumber);
        if (order == null) {
            return ServerResponseEntity.showFailMsg("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限申请退款");
        }

        faceDesignOrderService.applyRefund(orderNumber, userId, reason);
        return ServerResponseEntity.success();
    }

    /**
     * 获取订单统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取订单统计信息" , description = "获取订单统计信息")
    public ServerResponseEntity<Object> statistics() {
        String userId = SecurityUtils.getUser().getUserId();
        Object statistics = faceDesignOrderService.getOrderStatistics(userId);
        return ServerResponseEntity.success(statistics);
    }

    /**
     * 查询快递物流信息
     */
    @GetMapping("/expressQuery")
    @Operation(summary = "查询快递物流信息" , description = "查询快递物流信息")
    @Parameter(name = "orderNumber", description = "订单编号", required = true)
    public ServerResponseEntity<ExpressQueryDto> expressQuery(@RequestParam("orderNumber") String orderNumber) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesignOrder order = faceDesignOrderService.getByOrderNumber(orderNumber);
        if (order == null) {
            return ServerResponseEntity.showFailMsg("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限查询快递信息");
        }

        // 检查订单是否有快递信息
        if (StrUtil.isBlank(order.getExpressCompany()) || StrUtil.isBlank(order.getTrackingNumber())) {
            return ServerResponseEntity.showFailMsg("该订单暂无快递信息");
        }

        // 调用快递100 API查询物流信息
        ExpressQueryParam param = new ExpressQueryParam();
        param.setExpressCompanyCode(order.getExpressCompany());
        param.setExpressNumber(order.getTrackingNumber());

        ExpressQueryDto expressInfo = express100Service.queryExpress(param);
        return ServerResponseEntity.success(expressInfo);
    }

    /**
     * 查询快递状态
     */
    @GetMapping("/expressStatus")
    @Operation(summary = "查询快递状态" , description = "查询快递状态")
    @Parameter(name = "orderNumber", description = "订单编号", required = true)
    public ServerResponseEntity<Object> expressStatus(@RequestParam("orderNumber") String orderNumber) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesignOrder order = faceDesignOrderService.getByOrderNumber(orderNumber);
        if (order == null) {
            return ServerResponseEntity.showFailMsg("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限查询快递状态");
        }

        Object expressStatus = faceDesignOrderService.getExpressStatus(orderNumber);
        return ServerResponseEntity.success(expressStatus);
    }
}
